﻿Imports SmartStats.centralTendency
Imports SmartStats.dispersion
Public Class correlation
    Public Function covariance(ByVal in1() As Double, ByVal in2() As Double) As Double
        If in1.GetLength(0) <> in2.GetLength(0) Then
            Throw New System.Exception("An exception has occurred.Size of vectors do not match")
            Exit Function
        End If
        Dim sum As Double = 0
        For i As Integer = 0 To in1.GetLength(0) - 1
            sum = sum + ((in1(i) - in1.Average) * (in2(i) - in2.Average))
        Next
        Return sum / (in1.GetLength(0) - 1)
    End Function

    Public Function PearsonCorrelation(ByVal in1() As Double, ByVal in2() As Double) As Double
        If in1.GetLength(0) <> in2.GetLength(0) Then
            Throw New System.Exception("An exception has occurred.Size of vectors do not match")
            Exit Function
        End If
        Dim objDisperson As New dispersion
        Return covariance(in1, in2) / (objDisperson.StdDev(in1) * objDisperson.StdDev(in2))
    End Function

    Public Function CoeifficientOfDetermination(ByVal observed() As Double, ByVal predicted() As Double) As Double
        If observed.GetLength(0) <> predicted.GetLength(0) Then
            Throw New System.Exception("An exception has occurred.Size of vectors do not match")
            Exit Function
        End If
        Dim sumOfSquares As Double = 0
        Dim residualSumofSquares As Double = 0
        For i As Integer = 0 To observed.GetLength(0) - 1
            sumOfSquares = sumOfSquares + (observed(i) - observed.Average) ^ 2
            residualSumofSquares = residualSumofSquares + (predicted(i) - observed.Average) ^ 2
        Next
        Return (1 - (residualSumofSquares / sumOfSquares))
    End Function

    Public Function ConcordanceCorrelationCoeff(ByVal in1() As Double, ByVal in2() As Double) As Double
        If in1.GetLength(0) <> in2.GetLength(0) Then
            Throw New System.Exception("An exception has occurred.Size of vectors do not match")
            Exit Function
        End If
        Dim objDispersion As New dispersion
        Return (2 * covariance(in1, in2) / (objDispersion.Variance(in1) + objDispersion.Variance(in2) + (in1.Average - in2.Average) ^ 2))
    End Function

End Class
